package genedit.controller.interfaceActions;

import genedit.gui.GFileChooser;
import genedit.gui.GMainFrame;
import genedit.model.Project;
import genedit.model.Workspace;

import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;

import javax.swing.AbstractAction;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.KeyStroke;

/**
 * Akcija zadužena za otvaranje projekta.
 * 
 * @author Nikola
 * @version 1.1 15/12/13
 */
public class GOpenA extends AbstractAction {
	private static final long serialVersionUID = 1L;

	protected static GOpenA gOpenA = null;

	protected GOpenA() {
		putValue(NAME, "Open");
		putValue(SHORT_DESCRIPTION, "Open");
		putValue(SMALL_ICON, new ImageIcon("resources/icons/opened.png"));
		putValue(MNEMONIC_KEY, KeyEvent.VK_O);
		putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke("control O"));
	}

	public static AbstractAction getInstance() {
		if (gOpenA == null)
			gOpenA = new GOpenA();
		return gOpenA;
	}

	/**
	 * Akcija otvara dijalog gde korisnik pretražuje sistem datoteka. Ukoliko
	 * izabere projekat koji je ranije sačuvan on biva otvoren u stablu
	 * hijerarhije.
	 */
	@Override
	public void actionPerformed(ActionEvent e) {
		if (GFileChooser.getInstance(false).showOpenDialog(GMainFrame.getInstance()) == JFileChooser.APPROVE_OPTION) {
			File projectFile = GFileChooser.getInstance(false).getSelectedFile();

			if (projectFile.exists()) {
				Project project = null;
				try {
					if (projectFile.getCanonicalPath().contains(".xml")) {
						BufferedReader in = new BufferedReader(new InputStreamReader(
								new FileInputStream(projectFile)));
						project = (Project) Workspace.getInstance().getXstream().fromXML(in);
					} else {
						ObjectInputStream in = null;
						in = new ObjectInputStream(new FileInputStream(
								projectFile.getCanonicalPath()));
						project = (Project) in.readObject();
						in.close();
					}
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				} catch (ClassNotFoundException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}

				try {
					project.setPath(projectFile.getCanonicalPath());
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}

				Workspace.getInstance().addProjects(project);
				project.setParent(Workspace.getInstance());
			}
		}

		GFileChooser.getInstance(false).setCurrentDirectory(Workspace.getInstance().getPath());
	}
}